package org.springbus.habit.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springbus.habit.emus.ResponseCode;
import org.springbus.habit.entity.ConsumerInfo;
import org.springbus.habit.entity.Department;
import org.springbus.habit.entity.EmployeeInfo;
import org.springbus.habit.entity.PlanInfo;
import org.springbus.habit.service.ConsumerInfoService;
import org.springbus.habit.service.DepartmentService;
import org.springbus.habit.service.EmployeeInfoService;
import org.springbus.habit.service.PlanInfoService;
import org.springbus.habit.web.request.PlanInfoRequest;
import org.springbus.habit.web.response.CommonResponse;
import org.springbus.habit.web.response.PageResponse;
import org.springbus.habit.web.response.PlanResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 跟进计划 前端控制器
 * </p>
 *
 * @author Mr.Han
 * @since 2024-05-16
 */
@Tag(name = "跟进计划")
@RestController
public class PlanInfoController {

    @Resource
    private ConsumerInfoService consumerInfoService;

    @Resource
    private PlanInfoService planInfoService;

    @Resource
    private EmployeeInfoService employeeInfoService;

    @Resource
    private DepartmentService departmentService;

    @GetMapping("/admin/acl/plan/{page}/{limit}")
    @Operation(summary = "分页查询计划信息")
    public PageResponse<PlanResponse> getPageList(@Parameter(description = "当前页码", required = true) @PathVariable Long page,
                                                  @Parameter(description = "每页条数", required = true) @PathVariable Long limit,
                                                  @Parameter(description = "计划内容") String content) {

        Page<PlanInfo> infoPage = planInfoService.page(new Page<>(page, limit), new QueryWrapper<PlanInfo>()
                .likeRight(StringUtils.isNoneBlank(content),"plan_content", content).eq("deleted", false));
        if (CollectionUtils.isEmpty(infoPage.getRecords())) {
            return new PageResponse<>(Lists.newArrayList(), 0L);
        }
        List<Long> cusIds = infoPage.getRecords().stream().map(PlanInfo::getConsumerId).map(Long::valueOf).toList();
        List<ConsumerInfo> consumerInfos = consumerInfoService.listByIds(cusIds);
        List<Long> userIds = infoPage.getRecords().stream().map(PlanInfo::getUserId).toList();
        List<EmployeeInfo> employeeInfos = employeeInfoService.listByIds(userIds);
        List<Long> depIds = Optional.of(employeeInfos).orElse(Lists.newArrayList()).stream()
                .filter(e -> Objects.equals(e.getDeleted(), false)).map(EmployeeInfo::getDepId).toList();
        List<Department> departments = departmentService.listByIds(depIds);
        Map<Long, Department> departmentMap = Optional.ofNullable(departments).orElse(Lists.newArrayList()).stream()
                .filter(e -> Objects.equals(e.getDeleted(), false))
                .collect(Collectors.toMap(Department::getId, e -> e, (k1, k2) -> k1));
        Map<Long, EmployeeInfo> employeeInfoMap = Optional.of(employeeInfos).orElse(Lists.newArrayList()).stream()
                .filter(e -> Objects.equals(e.getDeleted(), false))
                .collect(Collectors.toMap(EmployeeInfo::getId, e -> e, (k1, k2) -> k1));
        Map<Long, ConsumerInfo> cusMap = Optional.ofNullable(consumerInfos).orElse(Lists.newArrayList()).stream()
                .filter(e -> Objects.equals(e.getDeleted(), false))
                .collect(Collectors.toMap(ConsumerInfo::getId, e -> e, (k1, k2) -> k1));
        List<PlanResponse> list = infoPage.getRecords().stream().map(p -> {
            String status = Objects.equals(p.getStatus(), 0) ? "未执行" : Objects.equals(p.getStatus(), 1) ? "执行中" : "执行完毕";
            EmployeeInfo employeeInfo = employeeInfoMap.getOrDefault(p.getUserId(), new EmployeeInfo());
            return new PlanResponse()
                    .setId(p.getId())
                    .setPlanContent(p.getPlanContent())
                    .setUserName(employeeInfo.getName())
                    .setUserId(employeeInfo.getId())
                    .setConsumerName(cusMap.getOrDefault(Long.valueOf(p.getConsumerId()), new ConsumerInfo()).getUsername())
                    .setConsumerId(Long.valueOf(p.getConsumerId()))
                    //计划状态 0-未执行 1-执行中 2-执行完毕
                    .setStatus(status)
                    .setDepartmentName(departmentMap.getOrDefault(employeeInfo.getDepId(), new Department()).getName())
                    .setGmtCreate(p.getGmtCreate())
                    .setGmtModified(p.getGmtModified());
        }).toList();
        return new PageResponse<>(list, infoPage.getTotal());

    }

    @PutMapping("/admin/acl/plan/update")
    @Operation(summary = "修改计划信息")
    public CommonResponse<Boolean> updatePlan(@Parameter(description = "计划信息", required = true) @RequestBody PlanInfoRequest request) {
        if (Objects.isNull(request) || Objects.isNull(request.getId())) {
            return new CommonResponse<>(ResponseCode.SYSTEM_ERROR);
        }
        PlanInfo info=new PlanInfo();
        BeanUtils.copyProperties(request,info);
        info.setGmtModified(new Date());
        //0-未执行 1-执行中 2-执行完毕
        Integer status=StringUtils.equals("未执行",request.getStatus())?0
                :StringUtils.equals("执行中",request.getStatus())?1:2;
        info.setStatus(status);
//        List<ConsumerInfo> infos = consumerInfoService.list(new QueryWrapper<ConsumerInfo>().eq("username", info.getConsumerName()).eq("deleted", false));
//        if (CollectionUtils.isEmpty(infos)){
//            return new CommonResponse<>(ResponseCode.SYSTEM_ERROR);
//        }
//        info.setConsumerId(String.valueOf(infos.get(0).getId()));
        planInfoService.update(info, new QueryWrapper<PlanInfo>().eq("id", info.getId()));
        return new CommonResponse<>(true);
    }

    @PutMapping("/admin/acl/plan/save")
    @Operation(summary = "保存计划信息")
    public CommonResponse<Boolean> savePlan(@Parameter(description = "计划信息", required = true) @RequestBody PlanInfo info) {
        if (Objects.isNull(info)) {
            return new CommonResponse<>(ResponseCode.SYSTEM_ERROR);
        }
        info.setGmtCreate(new Date());
//        List<ConsumerInfo> infos = consumerInfoService.list(new QueryWrapper<ConsumerInfo>().eq("username", info.getConsumerName()).eq("deleted", false));
//        if (CollectionUtils.isEmpty(infos)){
//            return new CommonResponse<>(ResponseCode.SYSTEM_ERROR);
//        }
//        info.setConsumerId(String.valueOf(infos.get(0).getId()));
        planInfoService.save(info);
        return new CommonResponse<>(true);
    }

    @DeleteMapping("/admin/acl/plan/remove/{id}")
    @Operation(summary = "删除计划信息")
    public CommonResponse<Boolean> removeUser(@Parameter(description = "计划ID", required = true) @PathVariable String id) {
        planInfoService.update(new PlanInfo().setDeleted(true).setGmtModified(new Date()), new QueryWrapper<PlanInfo>()
                .eq("id", id).eq("deleted", false));
        return new CommonResponse<>(true);
    }

    @DeleteMapping("/admin/acl/plan/batchRemove")
    @Operation(summary = "批量删除计划信息")
    public CommonResponse<Boolean> removeUser(@Parameter(description = "计划ID列表", required = true)@RequestBody ArrayList<String> userIds) {
        planInfoService.updateBatchById(userIds.stream().map(Long::valueOf).map(e -> new PlanInfo().setId(e)
                .setDeleted(true)
                .setGmtModified(new Date())).toList());
        return new CommonResponse<>(true);
    }
}
